//
//  CustomizedViewController.m
//  GAMCAfterSales
//
//  Created by BigAmazing on 2018/7/16.
//  Copyright © 2018年 glendale. All rights reserved.
//

#import "CustomizedViewController.h"
#import "popContentViewController.h"
#import "DDPopoverBackgroundView.h"
#import "MainMenuDataModel.h"
#define WorkHourLimit     @"0123456789."
#define RepairCodeLimit @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"

//// 设置不同的按钮
//typedef NS_ENUM(NSInteger,BtnNames) {
//    BtnNamePrice      = 0, // 单价按钮
//    BtnNameCostDifferent  = 1, // 费用区分
//    BtnNameRepairDifferent     = 2  // 维修区分
//};
@interface CustomizedViewController ()<ContentViewControllerDelegate,UITextFieldDelegate>{
    //下拉菜单属性
    UIPopoverController *popCon;
}

@property(nonatomic,strong)popContentViewController *contentCon;


/**
 维修代码
 */
@property (weak, nonatomic) IBOutlet UITextField *repairCodeText;
/**
 维修名称
 */
@property (weak, nonatomic) IBOutlet UITextField *repairNameText;
/**
 标准工时
 */
@property (weak, nonatomic) IBOutlet UITextField *workHourText;
/**
 工时单价
 */
@property(nonatomic,strong)NSMutableArray *labourPrices;
@property (weak, nonatomic) IBOutlet UIButton *workPriceBtn;
/**
 工时总费用
 */
@property (weak, nonatomic) IBOutlet UILabel *TotalCostLbl;

/**
 费用区分
 */
@property(nonatomic,strong)NSMutableDictionary *chargeDiff;
@property(nonatomic,strong)NSMutableArray *chargeDiffKeys;
@property (weak, nonatomic) IBOutlet UIButton *costDifferentBtn;
/**
 维修区分
 */
@property(nonatomic,strong)NSMutableArray *repairTypeNames;
@property(nonatomic,strong)NSMutableDictionary *repairTypeDic;
@property (weak, nonatomic) IBOutlet UIButton *repairDifferentBtn;
/**
 取消按钮
 */
@property (weak, nonatomic) IBOutlet UIButton *canelBtn;
/**
 确定按钮
 */
@property (weak, nonatomic) IBOutlet UIButton *makeSureBtn;

@end

@implementation CustomizedViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.workHourText.delegate = self;
    self.repairCodeText.delegate  =self;
    self.repairNameText.delegate = self;
    [self.workHourText addTarget:self action:@selector(textFieldValueChange:) forControlEvents:UIControlEventAllEditingEvents];
    
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setViewNormal) name:UIKeyboardWillHideNotification object:nil];
    
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    NSArray * repairArr = modelIns.repairProjects;
    NSString * labour_code = @"LSDYP0001";
    NSString * Nlabour_code;
    for (NSDictionary * dic in repairArr) {
        if ([dic[@"LABOUR_CODE"] containsString:@"LSDYP"]) {
            Nlabour_code = dic[@"LABOUR_CODE"];
        }
    }
    if (Nlabour_code.length >0) {
        NSString * str1 =  [Nlabour_code substringFromIndex:Nlabour_code.length-4];
        NSInteger intString = [str1 integerValue];
        intString = intString+1;
        Nlabour_code = [NSString stringWithFormat:@"LSDYP%04ld",intString];
        self.repairCodeText.text =Nlabour_code;
    }else{
        self.repairCodeText.text =labour_code;
    }
    self.repairCodeText.enabled = NO;

}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}
//视图回归正常状态
-(void)setViewNormal
{
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    CGRect rect = CGRectMake(0.0f, 0.0f, self.view.superview.frame.size.width, self.view.superview.frame.size.height);
    self.view.superview.frame = rect;
    [UIView commitAnimations];
}

-(void)computeAmout{
    double stdHour = [self.workHourText.text doubleValue];
    double price = [self.workPriceBtn.currentTitle doubleValue];
    self.TotalCostLbl.text = [NSString stringWithFormat:@"%.2f",stdHour * price];
}

-(void)textFieldValueChange:(UITextField *)textField{
    if (self.workPriceBtn.titleLabel.text.length>0 && textField.text.length>0) {
        [self computeAmout];
    }
}

- (IBAction)costDiffrentClick:(UIButton *)sender {
    //创建下拉菜单
    _contentCon.list = nil;
    [self createThePopViewControl:sender];
    NSArray *source = self.chargeDiffKeys;
    _contentCon.list = source;
    [_contentCon.myTableView reloadData];
}

- (IBAction)repairDiffrentClick:(UIButton *)sender {
    //创建下拉菜单
    _contentCon.list = nil;
    [self createThePopViewControl:sender];
    NSArray *source = self.repairTypeNames;
    _contentCon.list = source;
    [_contentCon.myTableView reloadData];
}

- (IBAction)priceClick:(UIButton *)sender {
    //创建下拉菜单
    _contentCon.list = nil;
    [self createThePopViewControl:sender];
    NSArray *source = self.labourPrices;
    _contentCon.list = source;
    [_contentCon.myTableView reloadData];

}

- (IBAction)canelClick:(UIButton *)sender {
    if (self.delegate && [self.delegate respondsToSelector:@selector(ClickCanelBtn)]) {
        [self.delegate ClickCanelBtn];
    }
}
-(NSString *)getErrorMsg{
    NSString *msg = nil;
    if (self.repairNameText.text.length<=0) {
        msg = @"请输入维修项目名称！";
    }else if (self.repairCodeText.text.length<=0){
        msg = @"请输入维修项目代码！";
    }else if (self.workHourText.text.length<=0){
        msg = @"请输入标准工时！";
    }else if (self.workPriceBtn.currentTitle.length<=0){
        msg = @"请选择工时单价！";
    }else if (self.repairDifferentBtn.currentTitle.length<=0){
        msg = @"请选择维修分类！";
    }else if (self.costDifferentBtn.currentTitle.length<=0){
        msg = @"请选择费用区分！";
    }
    return msg;
}
- (IBAction)makeSureClick:(UIButton *)sender {
    NSString *msg = [self getErrorMsg];
    if (msg) {
        UIAlertView *alerVeiw = [[UIAlertView alloc] initWithTitle:@"提示信息" message:msg delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alerVeiw show];
        return;
    }
    NSMutableDictionary * newData = [[NSMutableDictionary alloc]init];
    NSString *chargeDiffVal = self.chargeDiff[self.costDifferentBtn.titleLabel.text];
     NSString *repairTypeCode = self.repairTypeDic[self.repairDifferentBtn.titleLabel.text];

    [newData setValue:@"" forKey:@"ITEM_ID"];//id
    [newData setValue:@"A" forKey:@"STATUS"];//状态
    [newData setValue:chargeDiffVal forKey:@"CHARGE_PARTITION_CODE"];//收费区分
    newData[@"REPAIR_TYPE_CODE"] = repairTypeCode;//维修分类

    [newData setValue:self.workHourText.text forKey:@"STD_LABOUR_HOUR"];//标准工时
    [newData setValue:self.workPriceBtn.currentTitle forKey:@"LABOUR_PRICE"];//工时单价
    [newData setValue:self.repairNameText.text forKey:@"LABOUR_NAME"];//维修项目名称
     [newData setValue:self.repairCodeText.text forKey:@"LABOUR_CODE"];//维修项目代码
    [newData setValue:self.TotalCostLbl.text forKey:@"LABOUR_AMOUNT"];//工时费
    [newData setValue:@1 forKey:@"DISCOUNT"];
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    [modelIns.repairProjects addObject:newData];
    
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(ClickMakeSureBtn)]) {
        [self.delegate ClickMakeSureBtn];
    }
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    // When the user presses return, take focus away from the text field so that the keyboard is dismissed.
    [self setViewNormal];
    [textField resignFirstResponder];
    
 
    return YES;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    int offset = 150;//键盘高度350
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyBoard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    float width = self.view.superview.frame.size.width;
    float height = self.view.superview.frame.size.height;
    if(offset > 0)
    {
        CGRect rect = CGRectMake(0.0f, -offset,width,height);
        self.view.superview.frame = rect;
    }
    [UIView commitAnimations];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (textField == self.workHourText) {
        if (range.length == 1 && string.length == 0) {
            return YES;
        }
      else  if (self.workHourText.text.length >= 8) {
            self.workHourText.text = [textField.text substringToIndex:8];
            return NO;
            
        }
        return [self validateNumber:string withType:0];

    }else if (textField == self.repairNameText){
        if (range.length == 1 && string.length == 0) {
            return YES;
        }
        else  if (self.repairNameText.text.length >= 30) {
            self.repairNameText.text = [textField.text substringToIndex:30];
            return NO;
            
        }
    }else if (textField == self.repairCodeText){
        if (range.length == 1 && string.length == 0) {
            return YES;
        }
        else  if (self.repairCodeText.text.length >= 10) {
            self.repairCodeText.text = [textField.text substringToIndex:10];
            return NO;
            
        }
        return [self validateNumber:string withType:1];
    }
    return YES;
    
}

- (BOOL)validateNumber:(NSString*)number withType:(NSInteger)type{
    NSString * limit;
    // type = 1  表示维修代码  type= 0 表示工时
    if (type == 1) {
        limit = RepairCodeLimit;
    }else{
        limit = WorkHourLimit;
    }
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:limit];
    int i = 0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            break;
        }
        i++;
    }
    return res;
}


//创建下拉菜单方法
-(void)createThePopViewControl:(UIButton *)sender
{
    if (!_contentCon)
    {
        _contentCon=[[popContentViewController alloc] initWithNibName:@"popContentViewController" bundle:nil];
        _contentCon.delegate = self;
    }
    
    _contentCon.btnSender=sender;
    
    popCon = [[UIPopoverController alloc] initWithContentViewController:_contentCon];
    [DDPopoverBackgroundView setTintColor:[UIColor colorWithRed:234 green:248 blue:222 alpha:0.9]];
    [DDPopoverBackgroundView setArrowBase:30.0];//箭头
    [DDPopoverBackgroundView setArrowHeight:15.0];
    [DDPopoverBackgroundView setContentInset:1.0];
    
    [popCon setPopoverBackgroundViewClass:[DDPopoverBackgroundView class]];
    [popCon setPopoverContentSize:CGSizeMake(sender.frame.size.width, 200)];

    [popCon presentPopoverFromRect:CGRectMake(20, 10, 70, 20) inView:sender permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];
    
  
}
/**维修分类*/
-(NSMutableArray *)repairTypeNames{
    if (_repairTypeNames == nil) {
        _repairTypeNames= [NSMutableArray array];
        _repairTypeDic = [NSMutableDictionary dictionary];
        NSMutableArray *arr = [self readershuDICimform][@"TM_REPAIR_TYPE_ITEM"];
        for (NSDictionary *dic in arr) {
            NSString *name = dic[@"NAME"];
            NSString *val = dic[@"CODE"];
            [_repairTypeNames addObject:name];
            [_repairTypeDic setObject:val forKey:name];
        }
    }
    return _repairTypeNames;
}
/** 收费区分 */
-(NSMutableArray *)chargeDiffKeys{
    if (_chargeDiffKeys == nil) {
        _chargeDiffKeys= [NSMutableArray array];
        _chargeDiff = [NSMutableDictionary dictionary];
        NSMutableArray *arr = [self readershuDICimform][@"TM_CHARGE_PARTITION"];
        for (NSDictionary *dic in arr) {
            NSString *name = dic[@"NAME"];
            NSString *val = dic[@"CODE"];
            if ([name isEqualToString:@"自费"]||[name isEqualToString:@"免费"]||[name isEqualToString:@"保险"]||[name isEqualToString:@"店端活动"]||[name isEqualToString:@"客户活动"]) {
                [_chargeDiffKeys addObject:name];
                [_chargeDiff setObject:val forKey:name];
            }
            
        }
    }
    return _chargeDiffKeys;
}
/** 工时单价 */
-(NSMutableArray *)labourPrices{
    if (_labourPrices == nil) {
        _labourPrices= [NSMutableArray array];
        NSMutableArray *arr = [self readershuDICimform][@"TM_LABOUR_PRICE"];
        for (NSDictionary *dic in arr) {
            NSString *name = [dic[@"NAME"]stringValue];
            [_labourPrices addObject:name];
        }
    }
    return _labourPrices;
}


//弹出的回调方法
-(void)selectDelegate:(NSInteger)row btn:(UIButton *)btn
{
    NSString *key = nil;
//    if (btn == repairGroupBtn){
//
//        key = self.arrDisDataForCarType[row];
//    }else if (btn == charDiffBtn){
//        key = self.chargeDiffKeys[row];
//        [self labourPriceBtnControl:key];//选择收费区分的控制逻辑
//    }else if (btn == self.repairTypeBtn){
//        key = self.repairTypeNames[row];
//    }else if (btn == self.labourPriceBtn){
//        key = self.labourPrices[row];
//    }
    if (btn == self.workPriceBtn) {
        key = self.labourPrices[row];
        if (self.workHourText.text.length>0) {
            [self computeAmout];
        }
    }else if (btn == self.costDifferentBtn){
       key = self.chargeDiffKeys[row];

    }else if (btn == self.repairDifferentBtn){
        key = self.repairTypeNames[row];

    }
    [btn setTitle:key forState:UIControlStateNormal];

    
    //清空数据，退出控件
    [popCon dismissPopoverAnimated:YES];
    popCon = nil;
}




-(NSMutableDictionary *)readershuDICimform
{
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path=[paths objectAtIndex:0];
    NSString *str=[path stringByAppendingPathComponent:@"Dic.text"];
    dic=[NSMutableDictionary dictionaryWithContentsOfFile:str];
    return dic;
}


@end
